package com.cartoonrabbit.service.impl;

import com.cartoonrabbit.consts.WxAPIURL;
import com.cartoonrabbit.service.IWxPayService;
import com.cartoonrabbit.wxapp.properties.WxAppPayProperties;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class WxPayServiceImpl implements IWxPayService {

    @Autowired
    private WxAppPayProperties wxAppPayProperties;
    @Autowired
    private CloseableHttpClient closeableHttpClient;

    /**
     * 微信查单接口
     * @param orderNo
     * @return
     * @throws IOException
     */
    @Override
    public String queryOrderStatusByString(String orderNo) throws IOException {
        //向微信服务器查询订单状态
        String url=String.format(WxAPIURL.ORDER_QUERY_BY_NO,orderNo);
        HttpGet httpGet=new HttpGet(url.concat("?mchid=").concat(wxAppPayProperties.getMchId()));
        httpGet.setHeader("Accept", "application/json");
        CloseableHttpResponse response = closeableHttpClient.execute(httpGet);
        try {
            String bodyAsString = EntityUtils.toString(response.getEntity());
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { //处理成功
                return bodyAsString;
            }else {
                return null;
            }
        } finally {
            response.close();
        }
    }
}
